package han.chensing.latos.common.level.util;

import java.util.List;

import han.chensing.latos.common.level.function.TimeObject;
import han.chensing.latos.common.level.function.ListReference;

public class TimeUtil {

    public static <T extends TimeObject> T getLastHasTime(ListReference<T> reference, float time){
        if (reference==null)return null;
        for (int i = reference.size() - 1; i >= 0; i--) {
            T nowObject = reference.get(i);
            float objectTime = nowObject.getTime();
            if (time>=objectTime) return nowObject;
        }
        return null;
    }

    public static <T extends TimeObject> T getLastHasTime(List<T> list, float time){
        return getLastHasTime(ListReference.of(list),time);
    }

    public static <T extends TimeObject> int getLastHasTimeIndex(ListReference<T> reference,float time){
        if (reference==null)return -1;
        for (int i = reference.size() - 1; i >= 0; i--) {
            T nowObject = reference.get(i);
            float objectTime = nowObject.getTime();
            if (time>=objectTime) return i;
        }
        return -1;
    }

    public static <T extends TimeObject> T getNextHasTime(ListReference<T> reference, float time){
        for(int i=0;i<reference.size();i++){
            T timeObject=reference.get(i);
            float objectTime = timeObject.getTime();
            if (objectTime>time)return timeObject;
        }
        return null;
    }

    public static <T extends TimeObject> T getNextHasTime(List<T> list, float time){
        return getNextHasTime(ListReference.of(list),time);
    }

    public static <T extends TimeObject> T getNearestHasTime(ListReference<T> reference, float time){
        T lastTimeObject = getLastHasTime(reference,time);
        T nextTimeObject = getNextHasTime(reference,time);
        if (lastTimeObject==null&&nextTimeObject==null)return null;
        if (lastTimeObject == null)return nextTimeObject;
        if (nextTimeObject==null)return lastTimeObject;
        float distance1 = Math.abs(lastTimeObject.getTime() - time);
        float distance2 = Math.abs(nextTimeObject.getTime() - time);
        return distance1>distance2?nextTimeObject:lastTimeObject;
    }

    public static <T extends TimeObject> T getNearestHasTime(List<T> list, float time){
        return getNearestHasTime(new ListReference<>() {
            @Override
            public T get(int index) {
                return list.get(index);
            }

            @Override
            public int size() {
                return list.size();
            }
        },time);
    }
}
